package com.ilibrary.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ilibrary.base.MyWebAction;
import com.ilibrary.constants.MyConstants;
import com.ilibrary.constants.MyMsgConstants;
import com.ilibrary.service.AdminService;
import com.ilibrary.service.UserInfoService;
import com.ilibrary.utils.MD5Utils;
import com.ilibrary.web.dto.ResultDto;
import com.ilibrary.web.vo.AdminVO;
import com.ilibrary.web.vo.UserInfoVO;

public class DoLoginAction extends MyWebAction {
	
	private AdminService adminService;
	private UserInfoService userInfoService;

	public AdminService getAdminService() {
		return adminService;
	}
	public void setAdminService(AdminService adminService) {
		this.adminService = adminService;
	}
	public UserInfoService getUserInfoService() {
		return userInfoService;
	}
	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}

	@Override
	protected String doExecute(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		String userId = request.getParameter("userId");
		String userPassword = request.getParameter("userPassword");
		String userType = request.getParameter("userType");
		
		logger.info("-----------------------:"+userId);
		logger.info("-----------------------:"+userPassword);
		logger.info("-----------------------:"+userType);
		
		if(Integer.valueOf(userType) == MyConstants.ILIBRARY_LOGIN_TYPE_ADMIN) {
			ResultDto<AdminVO> resultDto =  adminService.findById(userId);
			if(resultDto.isSuccess()) {
				AdminVO adminVO = resultDto.getFirstResult();
				if(adminVO.getAdminPwd().equals(MD5Utils.generateForPassword(userPassword))) {
					adminVO.setAdminPwd(null);
					this.getSSN().setAttribute(MyConstants.ILIBRARY_LOGIN_ADMIN, adminVO);
					return "admin";
				}else {
					request.setAttribute("loginError", MyMsgConstants.LOGIN_ERROR_INVALID);
					return ERROR;
				}
			}else {
				request.setAttribute("loginError", resultDto.getMsg());
				return ERROR;
			}
		}else {
			ResultDto<UserInfoVO> resultDto = userInfoService.findById(userId);
			if(resultDto.isSuccess()) {
				UserInfoVO userInfoVO = resultDto.getFirstResult();
				if(userInfoVO.getUserPwd().equals(MD5Utils.generateForPassword(userPassword))) {
					userInfoVO.setUserPwd(null);
					this.getSSN().setAttribute(MyConstants.ILIBRARY_lOGIN_USER, resultDto.getFirstResult());
					return "client";
				}else {
					request.setAttribute("loginError", MyMsgConstants.LOGIN_ERROR_INVALID);
					return ERROR;
				}
			}else {
				request.setAttribute("loginError", resultDto.getMsg());
				return ERROR;
			}
		}
	}

}
